package org.csu.group4.jpetstore.service;

import org.csu.group4.jpetstore.mybatis.entity.ShopCart;
import org.csu.group4.jpetstore.persistence.ShopCartDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class ShopCartService {
    @Autowired
    ShopCartDAO shopCartDAO;

    public List<ShopCart>  getShopCartsByUsername(String username){
        return shopCartDAO.getAllByUsername(username);
    }

    public void addNewShopCart(ShopCart shopCart){
        if (isValid(shopCart))
            shopCartDAO.updateItem(shopCart);
        else
            shopCartDAO.insertNewItem(shopCart);
    }

    private boolean isValid(ShopCart shopCart){
        List<ShopCart> shopCarts= getShopCartsByUsername(shopCart.getAccountId());
        if (!Objects.requireNonNull(shopCarts).isEmpty()){
            for (ShopCart cart : shopCarts) {
                if (shopCart.getItemId().equals(cart.getItemId())){
                    return true;
                }
            }
            return false;
        }
        return false;
    }
    public void deleteItem(ShopCart shopCart){
        //200->未支付
        //203->已支付
        //500->删除
        shopCart.setStatus(500);
        shopCartDAO.updateStatus(shopCart);
    }

    public void payItem(ShopCart shopCart){
        //200->未支付
        //203->已支付
        //500->删除
        shopCart.setStatus(203);
        shopCartDAO.updateStatus(shopCart);
    }

    public ShopCart getItemByItemId(String username, String itemId){
        return shopCartDAO.getAllByUsernameAndItemId(username, itemId);
    }

//这是获取全部订单的方法
    //注意: 这里的用户名没有使用外键, 只有用户名, 需要自己通过SignOnService的getAccountByUsername获取Account对象
    public List<ShopCart> getAll(){
        return shopCartDAO.getAll();
    }
}
